import {observable,action,computed} from "mobx"
import {axios} from "&/axios"

class Cart{
    @observable cartlist=[];

    @action getCartList=(url)=>{
        axios.post(url).then(res=>{
            this.cartlist=res.data.result
        })
    }
    @action getCartListSync = payload=>{
        this.cartlist = payload;
    }
    @action delOneGood=(goodId)=>{
        axios.post("/api/delonegood",{
            goodId
        }).then(res=>{
            if(res.data.type){
                this.cartlist=this.cartlist.filter(item=>item.goodId!=goodId)
            }
        })
    }
    @action changeOneCount=(count,goodId)=>{
        axios.post("/api/changeonecount",{
            goodId,
            count
        }).then(res=>{
            if(res.data.type){
                this.cartlist=this.cartlist.map(item=>{
                    if(item.goodId==goodId){
                        item.count=count*1
                    }
                    return item;
                })
            }
        })
    }
    @action changeOneCheck=(checked,goodId)=>{
        axios.post("/api/changeonecheck",{
            ischeck:checked,
            goodId
        }).then(res=>{
            if(res.data.type){
                this.cartlist=this.cartlist.map(item=>{
                    if(item.goodId==goodId){
                        item.ischeck=checked
                    }
                    return item;
                })
            }
        })
    }
    @action changeDelCheck=()=>{
        this.cartlist.forEach(item=>{
            if(item.ischeck){
                axios.post("/api/delchecked").then(res=>{
                    if(res.data.type){
                        this.cartlist = this.cartlist.filter(item=>!item.ischeck); 
                    }
                })
            }
        })
        
    }
    @computed get total(){
        var total=0;
        this.cartlist.forEach(item=>{
            if(item.ischeck){
                total +=item.count*item.good.price*1;
            }
        })
        return total;
    }
    @computed get carnum(){
        var carnum=0;
        this.cartlist.forEach(item=>{
            if(item.ischeck){
                carnum +=item.count;
            }
        })
        return carnum
    }
    @computed get quan(){
        var quan  = true;
        this.cartlist.forEach(item=>{
            if(!item.ischeck){
                quan = false;
            }
        })
        return quan;
    }
    set quan(newVal){
        // ajax 
        axios.post("/api/changeonecheck",{
            ischeck:newVal
        }).then(res=>{
            if(res.data.type){
                this.cartlist = this.cartlist.map(item=>{
                    item.ischeck = newVal;
                    return item;
                }); 
            }
        })
    }

}
export default new Cart();